package com.hm.pan.controller;

import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hm.pan.annotation.CheckLogin;
import com.hm.pan.model.FileInfo;
import com.hm.pan.model.Offline;
import com.hm.pan.model.OfflineHistory;
import com.hm.pan.model.ResultObj;
import com.hm.pan.model.User;
import com.hm.pan.model.UserFile;
import com.hm.pan.service.FileInfoService;
import com.hm.pan.service.OfflineHistoryService;
import com.hm.pan.service.OfflineService;
import com.hm.pan.service.UserFileService;
import com.hm.pan.task.OfflineThread;
import com.hm.pan.task.OfflineThread.FailCallback;
import com.hm.pan.task.OfflineThread.SuccessCallback;
import com.hm.pan.util.HttpURLUtil;
import com.hm.pan.util.StringUtil;
import com.hm.pan.util.UserFileUtil;

@RestController
@RequestMapping("offline")
@CheckLogin
public class OfflineDownload {

	@Resource
	private UserFileService userFileService;
	@Resource
	private OfflineService offlineService;
	@Resource
	private OfflineHistoryService offlineHistoryService;
	@Resource
	private FileInfoService fileInfoService;

	private String tempDir = "offline_download/";

	/**
	 * 添加离线下载任务
	 * 下载过的任务，直接插入用户文件表，不重复下载
	 */
	@PostMapping("addOfflineTask")
	public Object addOfflineTask(@RequestParam("url") String url, @RequestParam("filename") String filename,
			HttpSession session) {
		ResultObj resultObj = new ResultObj();
		User user = (User) session.getAttribute("user");

		if (StringUtil.isEmpty(url = HttpURLUtil.stripQueryString(url)) || StringUtil.isEmpty(filename)) {
			resultObj.setStatusCode(400);
			resultObj.setMessage("缺少参数");
			return resultObj;
		}

		OfflineHistory offlineHistory = new OfflineHistory();
		offlineHistory.setUserId(user.getUserId());
		offlineHistory.setOfflineStatus(false);
		offlineHistory.setOfflineTime(new Timestamp(System.currentTimeMillis()));

		try {
			if (!offlineHistoryService.insertOfflineHistory(offlineHistory)) {
				resultObj.setStatusCode(500);
				resultObj.setMessage("创建离线下载历史记录失败");
				return resultObj;
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultObj.setStatusCode(500);
			resultObj.setMessage("创建离线下载历史记录失败");
			return resultObj;
		}

		Offline offline = new Offline();
		try {
			offline.setUrl(DigestUtils.md5DigestAsHex(url.getBytes("UTF-8")));
			Offline offline2 = offlineService.findByUrl(offline);
			// 如果找得到，说明已经下载过了，直接插入到用户文件表
			if (offline2 != null) {
				// 插入到用户文件表中
				UserFile userFile = new UserFile();
				userFile.setUserId(user.getUserId());
				userFile.setFileId(offline2.getFileId());
				userFile.setFileName(filename);
				userFile.setUploadTime(new Timestamp(System.currentTimeMillis()));
				userFile.setFileType(true);
				userFile.setFatherId(0L);
				userFile.setIsDelete(false);
				userFileService.insertFile(userFile);

				resultObj.setStatusCode(200);
				resultObj.setMessage("下载完成");
				return resultObj;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		// 启动线程下载
		new Thread(new OfflineThread(url, new SuccessCallback() {
			// 成功回调
			@Override
			public void callback(byte[] data, String url) {
				if (!UserFileUtil.createTmpDir(tempDir)) {
					return;
				}

				// 物理路径
				String realName = tempDir + UUID.randomUUID().toString().replace("-", "");
				try (FileOutputStream fos = new FileOutputStream(realName)) {
					fos.write(data);

					// 插入文件数据
					FileInfo fileInfo = new FileInfo();
					fileInfo.setFilePath(realName);
					fileInfo.setFileMd5(DigestUtils.md5DigestAsHex(data));
					fileInfo.setFileSize((long) data.length);
					fileInfoService.insertFileInfo(fileInfo);

					// 更新下载状态
					offlineHistory.setOfflineStatus(true);
					offlineHistoryService.updateOfflineHistory(offlineHistory);

					// 插入到用户文件表中
					UserFile userFile = new UserFile();
					userFile.setUserId(user.getUserId());
					userFile.setFileId(fileInfo.getFileId());
					userFile.setFileName(filename);
					userFile.setUploadTime(new Timestamp(System.currentTimeMillis()));
					userFile.setFileType(true);
					userFile.setFatherId(0L);
					userFile.setIsDelete(false);
					userFileService.insertFile(userFile);

					// 记录下载数据，下次就不用下载这个url了
					Offline offline = new Offline();
					offline.setUrl(DigestUtils.md5DigestAsHex(url.getBytes("UTF-8")));
					offline.setFileId(fileInfo.getFileId());
					offlineService.insertOffline(offline);
					System.err.println("===================离线下载完成=====================");
					System.err.println(realName);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new FailCallback() {
			// 失败回调
			@Override
			public void callback() {
			}
		})).start();

		resultObj.setStatusCode(201);
		resultObj.setMessage("创建下载成功");
		return resultObj;
	}

}
